#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ubuntu 路由器配置打包脚本 (Python 版本)
将 ubuntu-router-config 目录打包为 tar.gz 文件
"""

import os
import tarfile
import sys
from datetime import datetime
from pathlib import Path

def main():
    script_dir = Path(__file__).parent.absolute()
    source_dir = script_dir / "ubuntu-router-config"
    output_dir = script_dir
    
    # 检查源目录是否存在
    if not source_dir.exists():
        print(f"错误: 源目录不存在: {source_dir}")
        sys.exit(1)
    
    # 生成压缩包名称
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    archive_name = f"ubuntu-router-config_{timestamp}.tar.gz"
    archive_path = output_dir / archive_name
    
    # 排除的文件和目录
    exclude_patterns = [
        "__pycache__",
        ".git",
        ".gitignore",
        "*.pyc",
        ".DS_Store",
        "*.swp",
        "*.swo",
        "*~",
        ".idea",
        ".vscode",
        "config.yaml",  # 排除实际配置文件，只保留示例（config.yaml.example 会被打包）
    ]
    
    print("=" * 60)
    print("Ubuntu 路由器配置打包脚本")
    print("=" * 60)
    print(f"源目录: {source_dir}")
    print(f"输出目录: {output_dir}")
    print(f"压缩包名称: {archive_name}")
    print()
    print("排除规则:")
    for pattern in exclude_patterns:
        print(f"  - {pattern}")
    print()
    
    # 创建压缩包
    print("正在创建压缩包...")
    
    def filter_func(tarinfo):
        """过滤函数，排除不需要的文件"""
        name = tarinfo.name
        
        # 排除根目录外的内容
        if name == "ubuntu-router-config" or name == "ubuntu-router-config/":
            return tarinfo
        
        # 移除前缀（处理 Windows 和 Linux 路径）
        if name.startswith("ubuntu-router-config/"):
            rel_path = name[len("ubuntu-router-config/"):]
        elif name.startswith("ubuntu-router-config\\"):
            rel_path = name[len("ubuntu-router-config\\"):]
        else:
            rel_path = name
        
        # 标准化路径分隔符
        rel_path = rel_path.replace("\\", "/")
        
        # 检查是否应该排除
        for pattern in exclude_patterns:
            # 移除通配符用于匹配
            clean_pattern = pattern.replace("*", "")
            
            # 跳过 config.yaml.example（确保它被打包）
            if "config.yaml.example" in rel_path:
                continue
            
            # 检查文件名或路径中是否包含排除模式
            if clean_pattern in rel_path:
                # 检查是否是整个文件名或目录名匹配
                path_parts = rel_path.split("/")
                if any(clean_pattern in part or part.endswith(clean_pattern) for part in path_parts):
                    return None
        
        return tarinfo
    
    try:
        with tarfile.open(archive_path, "w:gz") as tar:
            # 添加整个目录
            tar.add(source_dir, arcname="ubuntu-router-config", filter=filter_func)
        
        # 获取文件大小
        archive_size = archive_path.stat().st_size
        size_mb = archive_size / (1024 * 1024)
        
        print()
        print("=" * 60)
        print("打包完成！")
        print("=" * 60)
        print(f"压缩包: {archive_name}")
        print(f"大小: {size_mb:.2f} MB ({archive_size:,} 字节)")
        print(f"位置: {archive_path}")
        print()
        
        # 显示压缩包内容摘要（前20项）
        print("压缩包内容（前20项）:")
        with tarfile.open(archive_path, "r:gz") as tar:
            members = tar.getmembers()[:20]
            for member in members:
                print(f"  {member.name}")
            total_count = len(tar.getmembers())
            if total_count > 20:
                print(f"  ... (共 {total_count} 项)")
        print()
        
    except Exception as e:
        print(f"错误: 打包失败 - {e}")
        if archive_path.exists():
            archive_path.unlink()
        sys.exit(1)

if __name__ == '__main__':
    main()

